package com.aaa.sso.config;

import com.aaa.sso.util.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @fileName.ShiroConfig
 * @description:
 * @author:zwl
 * @createTime:2020/11/13 13:58
 * @version:1.0.0
 */
@Configuration
@Component
public class ShiroConfig {
    /**
     * 初始化shiro过滤工厂类
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        //实例化
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        //设置未认证的地址访问后跳转的路径
        //shiroFilterFactoryBean.setLoginUrl();
        //设置认证成功后的地址访问后跳转的路径
        //shiroFilterFactoryBean.setSuccessUrl();
        //访问未授权地址跳转的页面
        //shiroFilterFactoryBean.setUnauthorizedUrl();
        //设置SecurityManager

        //实例化map，不能使用HashMap，因为无序；要用LinkedHashMap，有序
        Map<String,String> filterMap=new LinkedHashMap<>();
        //anon 放行的路径
//        filterMap.put("/ms/news/**","anon");
//        filterMap.put("/cs/carController/**","anon");
//        filterMap.put("/ulactController/userLogin","anon");
        //authc 拦截的请求
        filterMap.put("/**","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        return shiroFilterFactoryBean;
    }

    /**
     * 初始化安全管理器
     * @return
     */
    @Bean
    public SecurityManager securityManager(){
        //实例化
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //设置realm
        securityManager.setRealm(myRealm());
        return securityManager;
    }

    /**
     * 实例化Realm(安全数据的链接桥梁)
     * @return
     */
    @Bean
    public MyRealm myRealm(){
        //实例化
        MyRealm myRealm=new MyRealm();
        //设置校验匹配器
        myRealm.setCredentialsMatcher(credentialsMatcher());
        return myRealm;
    }

    /**
     * 加密算法及类型设置类
     * @return
     */
    @Bean
    public CredentialsMatcher credentialsMatcher(){
        //实例化
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        //设置加密算法
        credentialsMatcher.setHashAlgorithmName("SHA-512");
        //设置hash次数
        credentialsMatcher.setHashIterations(1024);
        return credentialsMatcher;
    }
}
